package br.ucb.cesbdao.janelas;

import java.sql.SQLException;
import java.util.List;

import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;

import org.apache.log4j.Logger;

import br.ucb.cesbdao.beans.Grupo;
import br.ucb.cesbdao.controller.ControladorJanelas;
import br.ucb.cesbdao.enuns.EnumControleJanela;
import br.ucb.cesbdao.enuns.EnumFormatos;
import br.ucb.cesbdao.enuns.EnumLabelAndBotao;
import br.ucb.cesbdao.enuns.EnumMensagens;
import br.ucb.cesbdao.enuns.EnumResources;
import br.ucb.cesbdao.enuns.EnumTitulo;
import br.ucb.cesbdao.model.TrabalhadorModel;
import br.ucb.cesbdao.model.TrabalhadorPorGrupoModel;
import br.ucb.cesbdao.model.impl.TrabalhadorModelImpl;
import br.ucb.cesbdao.model.impl.TrabalhadorPorGrupoModelImpl;
import br.ucb.cesbdao.servicos.Servicos;
import br.ucb.cesbdao.visao.Visao;


@SuppressWarnings("serial")
public class JanelaListaGrupoByAtendente extends javax.swing.JFrame{
    
    
    final DefaultTableModel modelo = new DefaultTableModel();
    private List<Grupo> grupos  = null;
    static Logger logger = Servicos.carregaLog(JanelaListaGrupoByAtendente.class);
    public JanelaListaGrupoByAtendente() throws SQLException, ClassNotFoundException {
    	initComponents();
    	
        modelo.addColumn("Nº Grupo");
        modelo.addColumn("Nome");
        modelo.addColumn("Dia Semana");
        modelo.addColumn("Horário Inicial");
        modelo.addColumn("Status");
        
        tabela.getTableHeader().setReorderingAllowed(false);
        tabela.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        setResizable(false);
        
        this.setTitle(EnumTitulo.TITULO_GRUPO.getTitulo());
    }
    
    private void initComponents() {

        painelListar = new javax.swing.JPanel();
        painelFiltro = new javax.swing.JPanel();
        painelBusca = new javax.swing.JPanel();
        txt_busca = new javax.swing.JTextField();
        btn_buscarTrabalhador = new javax.swing.JButton();
        btn_pesquisar = new javax.swing.JButton();
        painelResultados = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabela = new javax.swing.JTable();
        btn_alterar = new javax.swing.JButton();
        btn_excluir = new javax.swing.JButton();
        btn_cancelar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setBounds(new java.awt.Rectangle(250, 25, 0, 0));

        painelFiltro.setBorder(javax.swing.BorderFactory.createTitledBorder(null, EnumLabelAndBotao.FILTRO.getTexto(), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font(EnumFormatos.FONTE_TAHOMA.getFormato(), 1, 12))); 

        painelBusca.setBorder(javax.swing.BorderFactory.createTitledBorder(null, EnumLabelAndBotao.SELECIONE_ATENDENTE.getTexto(), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font(EnumFormatos.FONTE_TAHOMA.getFormato(), 1, 11))); 

        txt_busca.setEditable(false);
        txt_busca.setBorder(javax.swing.BorderFactory.createTitledBorder(null, EnumLabelAndBotao.NOME_ATENDENTE.getTexto(), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font(EnumFormatos.FONTE_TAHOMA.getFormato(), 1, 11))); 

        btn_buscarTrabalhador.setIcon(new javax.swing.ImageIcon(getClass().getResource(EnumResources.ICONE_BUSCAR_PEQUENO.getCaminho()))); 
        btn_buscarTrabalhador.setText(EnumLabelAndBotao.SELECIONAR_APOIO.getTexto());
        btn_buscarTrabalhador.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
				try {
					btn_buscarTrabalhadorActionPerformed(evt);
				} catch (SQLException e) {
					logger.error(e.getMessage());
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					logger.error(e.getMessage());
					e.printStackTrace();
				}
            }
        });

        javax.swing.GroupLayout painelBuscaLayout = new javax.swing.GroupLayout(painelBusca);
        painelBusca.setLayout(painelBuscaLayout);
        painelBuscaLayout.setHorizontalGroup(
            painelBuscaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, painelBuscaLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(txt_busca, javax.swing.GroupLayout.DEFAULT_SIZE, 394, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btn_buscarTrabalhador)
                .addGap(18, 18, 18))
        );
        painelBuscaLayout.setVerticalGroup(
            painelBuscaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(painelBuscaLayout.createSequentialGroup()
                .addGroup(painelBuscaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(painelBuscaLayout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addComponent(btn_buscarTrabalhador))
                    .addGroup(painelBuscaLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(txt_busca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        btn_pesquisar.setIcon(new javax.swing.ImageIcon(getClass().getResource(EnumResources.ICONE_BUSCAR.getCaminho()))); 
        btn_pesquisar.setText(EnumLabelAndBotao.PESQUISAR.getTexto());
        btn_pesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                try {
					btn_pesquisarActionPerformed(evt);
				} catch (NumberFormatException e) {
					logger.error(e.getMessage());
					e.printStackTrace();
				} catch (SQLException e) {
					logger.error(e.getMessage());
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					logger.error(e.getMessage());
					e.printStackTrace();
				}
            }
        });

        javax.swing.GroupLayout painelFiltroLayout = new javax.swing.GroupLayout(painelFiltro);
        painelFiltro.setLayout(painelFiltroLayout);
        painelFiltroLayout.setHorizontalGroup(
            painelFiltroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(painelFiltroLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(painelBusca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(btn_pesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(21, Short.MAX_VALUE))
        );
        painelFiltroLayout.setVerticalGroup(
            painelFiltroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(painelFiltroLayout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addComponent(btn_pesquisar)
                .addContainerGap(38, Short.MAX_VALUE))
            .addGroup(painelFiltroLayout.createSequentialGroup()
                .addComponent(painelBusca, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        painelResultados.setBorder(javax.swing.BorderFactory.createTitledBorder(null, EnumLabelAndBotao.RESULTADOS.getTexto(), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font(EnumFormatos.FONTE_TAHOMA.getFormato(), 1, 12))); 

        tabela.setModel(modelo);

        jScrollPane1.setViewportView(tabela);

        btn_alterar.setIcon(new javax.swing.ImageIcon(getClass().getResource(EnumResources.ICONE_MODIFICAR.getCaminho()))); 
        btn_alterar.setText(EnumLabelAndBotao.ALTERAR.getTexto());
        btn_alterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                try {
					btn_alterarActionPerformed(evt);
				} catch (SQLException e) {
					logger.error(e.getMessage());
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					logger.error(e.getMessage());
					e.printStackTrace();
				}
            }
        });

        btn_excluir.setIcon(new javax.swing.ImageIcon(getClass().getResource(EnumResources.ICONE_LIXEIRA.getCaminho()))); 
        btn_excluir.setText(EnumLabelAndBotao.EXCLUIR.getTexto());
        btn_excluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                try {
					btn_excluirActionPerformed(evt);
				} catch (NumberFormatException e) {
					logger.error(e.getMessage());
					e.printStackTrace();
				} catch (SQLException e) {
					logger.error(e.getMessage());
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					logger.error(e.getMessage());
					e.printStackTrace();
				}
            }
        });

        btn_cancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource(EnumResources.ICONE_CANCELAR.getCaminho()))); 
        btn_cancelar.setText(EnumLabelAndBotao.CANCELAR.getTexto());
        btn_cancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_cancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout painelResultadosLayout = new javax.swing.GroupLayout(painelResultados);
        painelResultados.setLayout(painelResultadosLayout);
        painelResultadosLayout.setHorizontalGroup(
            painelResultadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(painelResultadosLayout.createSequentialGroup()
                .addGroup(painelResultadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(painelResultadosLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 732, Short.MAX_VALUE))
                    .addGroup(painelResultadosLayout.createSequentialGroup()
                        .addGap(180, 180, 180)
                        .addComponent(btn_alterar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btn_excluir)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btn_cancelar)))
                .addContainerGap())
        );
        painelResultadosLayout.setVerticalGroup(
            painelResultadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, painelResultadosLayout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(painelResultadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btn_excluir)
                    .addComponent(btn_cancelar)
                    .addComponent(btn_alterar))
                .addContainerGap())
        );

        javax.swing.GroupLayout painelListarLayout = new javax.swing.GroupLayout(painelListar);
        painelListar.setLayout(painelListarLayout);
        painelListarLayout.setHorizontalGroup(
            painelListarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(painelListarLayout.createSequentialGroup()
                .addGroup(painelListarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(painelListarLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(painelFiltro, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, painelListarLayout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addComponent(painelResultados, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        painelListarLayout.setVerticalGroup(
            painelListarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(painelListarLayout.createSequentialGroup()
                .addComponent(painelFiltro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(painelResultados, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(28, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(painelListar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(painelListar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        pack();
    }                                 

    private void btn_alterarActionPerformed(java.awt.event.ActionEvent evt) throws SQLException, ClassNotFoundException {
    	TrabalhadorModel model = new TrabalhadorModelImpl();
        if(tabela.getSelectedRow() == -1){
            Visao.showMessageWarning("Nenhum atendente foi selecionado", "Aviso do sistema");
            return;
        }
        Janela.setTxt_idTrabalhadorVinculaGrupo((model.consultaTrabalhador(JanelaBuscaAtendente.getIdTrabalhador())).getNome());
        Janela.setIdTrabalhadorVinculaGrupo(JanelaBuscaAtendente.getIdTrabalhador());
        Janela.setIdGrupoVinculaGrupo(getGrupoAt(tabela.getSelectedRow()).getIdGrupo());
        Janela.setTxt_idGrupoVinculaGrupo(getGrupoAt(tabela.getSelectedRow()).getNome());
        
        Janela.setAmbienteAlteracaoTrabalhadorVinculaGrupo();
        this.setVisible(false);
    }                                           

    private void btn_excluirActionPerformed(java.awt.event.ActionEvent evt) throws NumberFormatException, SQLException, ClassNotFoundException {  
    	TrabalhadorPorGrupoModel model = new TrabalhadorPorGrupoModelImpl();
        if(tabela.getSelectedRow() == -1){
            Visao.showMessageWarning(EnumMensagens.MSG_ALERTA_AFI_N_SELECIONADO.getMensagem(), "Aviso do sistema");
            return;
        }
        if((model.excluiTrabalhadorGrupo(Janela.getIdTrabalhadorVinculaGrupo(), Integer.parseInt(""+tabela.getValueAt(tabela.getSelectedRow(), 0)))) != 0)
        	Visao.showMessage(EnumMensagens.MSG_CONFIRMACAO_EXLCUIR_VINCULO.getMensagem(), "Aviso do Sistema");
        else
        	Visao.showMessageWarning(EnumMensagens.MSG_ALERTA_EXLCUIR_VINCULO.getMensagem(), "Aviso do Sistema");
        setVisible(false);
    }                                           

    private void btn_buscarTrabalhadorActionPerformed(java.awt.event.ActionEvent evt) throws SQLException, ClassNotFoundException {                                              
          setBuscando(true);
          ControladorJanelas.invokeJFrame(this.getClass().getSimpleName(), EnumControleJanela.JANELA_BUSCA_ATENDENTE.getNomeJanela());
    }                                             

	public static boolean isBuscando() {
		return buscando;
	}

	public static void setBuscando(boolean buscando) {
		JanelaListaGrupoByAtendente.buscando = buscando;
	}

	public static void setTxt_busca(String string) {
		txt_busca.setText(string);
	}
	public Grupo getGrupoAt(int row){
		return grupos.get(row);
	}
	private void btn_pesquisarActionPerformed(java.awt.event.ActionEvent evt) throws NumberFormatException, SQLException, ClassNotFoundException {
		TrabalhadorPorGrupoModel model = new TrabalhadorPorGrupoModelImpl();
		setBuscando(false);
        if(!(txt_busca.getText().isEmpty())){
        	modelo.setRowCount(0);
        	String diasSemana[] = {"Domingo","Segunda-feira", "Terça-feira", "Quarta-feira", "Quinta-feira","Sexta-feira","Sábado"};
        	grupos = model.consultaTrabalhadorGrupoByTrabalhadorId(JanelaBuscaAtendente.getIdTrabalhador());
        	for(Grupo grupo : grupos)
                modelo.addRow(new Object[]{grupo.getNumeroGrupo(), grupo.getNome(), diasSemana[grupo.getDiaSemana()-1], grupo.getHorarioInicial(), grupo.getStatus() == 'A'?"Ativo":"Inativo"});
        }
    }                                      

    private void btn_cancelarActionPerformed(java.awt.event.ActionEvent evt) {                                             
        setVisible(false);
    }                                            

    private static boolean buscando = false;
    private javax.swing.JButton btn_alterar;
    private javax.swing.JButton btn_buscarTrabalhador;
    private javax.swing.JButton btn_cancelar;
    private javax.swing.JButton btn_excluir;
    private javax.swing.JButton btn_pesquisar;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel painelBusca;
    private javax.swing.JPanel painelFiltro;
    private javax.swing.JPanel painelListar;
    private javax.swing.JPanel painelResultados;
    private javax.swing.JTable tabela;
    private static javax.swing.JTextField txt_busca;

}
